<template>
    <div class="product_management_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            row-id-key="product_id"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select="onSelect"
            @selection-change="onSelectionChange"
            @select-all="onSelectAll">
            <template #headerOperate>
                <el-button :disabled="!checkList.length" @click="onChange(1)">批量上架</el-button>
                <el-button :disabled="!checkList.length" @click="onChange(2)">批量下架</el-button>
                <el-button @click="ImportStore">导入产品</el-button>
                <el-button type="primary" @click="newProductList">新建产品</el-button>
            </template>
        </ZwTable>
    </div>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
    <!-- 预览弹窗 -->
    <productPopup ref="productPopupRef" :product-popup-data="productPopupData" />
    <!-- 导入产品弹窗 -->
    <Dialog :app-dialog="appDialog">
        <div class="dia_text" style="margin-bottom: 12px">1、请跟据产品模板进行填写</div>
        <div class="dia_text">2、上传导入产品模板</div>
        <div style="margin: 32px 0 24px; display: flex; align-items: center">
            上传文件
            <el-upload
                action=""
                accept=".xlsx,.xls"
                :on-change="handleFile"
                class="file"
                :auto-upload="false"
                :on-remove="del">
                <el-button>导入文件</el-button>
            </el-upload>
            <span style="color: #ff6b00; font-size: 12px; cursor: pointer" @click="download">下载模板</span>
        </div>
        <div v-if="formData.product_name" class="file_info">
            <span style="display: flex; align-items: center">
                <img src="@/assets/image/customer/xls_icon.png" />
                <span>{{ formData.product_name }}</span>
            </span>
            <el-icon class="del_icon" @click="del"><Delete /></el-icon>
        </div>
    </Dialog>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SALESLEADS_SALESMANAGEMENT_PRODUCT_MANAGEMENT' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import {
    CatetList,
    productList,
    productDel,
    productUpstate,
    productDownstate,
    productPreview,
    productImport
} from '@/api/salesleads/productmanagement/product';
import productPopup from './components/productPopup.vue';
import product from '@/api/salesleads/productmanagement/product';
import Dialog from '@/components/Dialog.vue';
import { uploadFile2 } from '@/api/common';
import type { UploadProps } from 'element-plus';
import { ref, reactive, computed, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { downFile } from '@/utils/utils';
const DeletdialogRef: any = ref(null);
const router = useRouter();
const isShow = ref(0);
const checkList = ref([]);
const delId = ref([]);
const productPopupRef: any = ref(null);
const productPopupData = ref([]);
const formData = reactive({
    product_url: '',
    product_name: ''
});

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const defaultParams = {
    product_name: '', //产品搜索
    state: 'all', //产品状态
    category_id: '', //产品品类
    price_range: '', //价格区间
    stock_qty_state: 'all' //库存状态
};
const groupOptions = ref([]);

const cateListMap = new Map();
const getCatetList = async (data: any) => {
    const res = await CatetList(data);
    groupOptions.value = res;
    for (const cateItem of res) {
        cateListMap.set(
            cateItem.id,
            cateItem.children.map((item: any) => item.id)
        );
    }
};
getCatetList();
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: true,
    label: 'name',
    value: 'id'
};
const tableRef = ref<HTMLElement | null>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '产品搜索',
            name: 'product_name',
            value: '',
            type: 'input',
            placeholder: '请输入产品名称'
        },
        {
            label: '产品状态',
            name: 'state',
            value: 'all',
            type: 'select',
            placeholder: '请选择',
            optionList: [
                { name: '全部', id: 'all' },
                { name: '上架', id: 2 },
                { name: '下架', id: 1 }
            ],
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '产品品类',
            name: 'category_id',
            value: [],
            type: 'cascader',
            props: defaultProps,
            collapseTags: true,
            collapseTagsTooltip: true,
            options: groupOptions.value,
            onChange: (val: any, formData: any) => {
                const childrenIds = [];
                for (const id of val) {
                    const ids = cateListMap.get(id);
                    if (ids) {
                        childrenIds.push(...ids);
                    }
                }
                formData?.category_id.splice(0, formData.category_id.length, ...[...val, ...childrenIds]);
            }
        },
        {
            label: '价格区间￥',
            name: 'price_range',
            value: [],
            type: 'section',
            isForbidNegativeNumber: true,
            placeholderBefore: '请输入金额',
            placeholderAfter: '请输入金额'
        },
        {
            label: '库存状态',
            name: 'stock_qty_state',
            value: 'all',
            type: 'select',
            placeholder: '请选择',
            optionList: [
                { name: '全部', id: 'all' },
                { name: '正常', id: 1 },
                { name: '无库存', id: 2 }
            ],
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    tableRef.value?.clearSelection();
    if (!v.state) {
        v.state = 'all';
    }
    if (!v.stock_qty_state) {
        v.stock_qty_state = 'all';
    }
    currentParams.value = v;
    state.searchParams = { ...deepCopy(defaultParams), ...v };
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = { ...deepCopy(defaultParams) };
    currentParams.value = null;
};

const onBtn = (row: any) => {
    return (
        <>
            <ElButton
                v-show={row.state == 1}
                size="small"
                onClick={() => {
                    delId.value = [row.product_id];
                    onChange(1);
                }}>
                上架
            </ElButton>
            <ElButton
                v-show={row.state !== 1}
                size="small"
                onClick={() => {
                    delId.value = [row.product_id];
                    onChange(2);
                }}>
                下架
            </ElButton>
            <ElButton
                size="small"
                disabled={row.state == 2}
                onClick={() => {
                    edit(row);
                }}>
                编辑
            </ElButton>
            <ElButton
                size="small"
                onClick={async () => {
                    look(row);
                }}>
                查看
            </ElButton>
            <ElButton
                size="small"
                onClick={() => {
                    preview(row);
                }}>
                预览
            </ElButton>
            <ElButton
                size="small"
                onClick={() => {
                    delId.value = row.product_id;
                    onChange(3);
                }}>
                删除
            </ElButton>
        </>
    );
};
// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'product_no',
        label: '产品编号',
        minWidth: 160,
        render({ row, column, index }) {
            return (
                <>
                    <div>{row.product_no}</div>
                </>
            );
        }
    },
    {
        prop: 'cover',
        label: '产品信息',
        minWidth: 220,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image-slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );

            return (
                <>
                    {row.cover == '' ? (
                        <div style="display: flex; align-items: center">
                            <el-image src="/static/file/pic.png" style="width: 48px; height: 48px"></el-image>
                            <span style="margin-left: 12px; flex: 1;">{row.product_name}</span>
                        </div>
                    ) : (
                        <div style="display: flex; align-items: center">
                            <ElImage
                                preview-src-list={[row.cover]}
                                preview-teleported={true}
                                src={row.cover}
                                fit="cover"
                                style="width: 48px; height: 48px; font-size: 49px"
                                vSlots={{ error: slotError }}
                            />
                            <span style="margin-left: 12px; flex: 1;">{row.product_name}</span>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'category_name',
        label: '品类',
        width: 200
    },
    {
        prop: 'stock_qty',
        label: '库存',
        width: 170
    },
    {
        prop: 'sale_qty',
        label: '销量',
        width: 170
    },
    {
        prop: 'sale_price_range',
        label: '售卖价格',
        width: 170
    },
    {
        prop: 'state_name',
        label: '上架状态',
        width: 170
    },
    {
        prop: 'stock_qty_state_name',
        label: '库存状态',
        width: 170
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 175
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return onBtn(row);
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    // 获取文件列表
    return productList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.product_id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.product_id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};

const onChange = (num: number) => {
    //1上架，2下架，3删除
    switch (num) {
        case 1:
            DeletdialogRef.value.appDialog.title = '上架提醒';
            DeletdialogRef.value.content = '确定上架所选产品吗？';
            break;
        case 2:
            DeletdialogRef.value.appDialog.title = '下架提醒';
            DeletdialogRef.value.content = '确定下架所选产品吗？';
            break;
        case 3:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '确认删除所选产品吗？';
            break;
    }
    isShow.value = num;
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = async () => {
    const params = delId.value.length ? delId.value : checkList.value;
    switch (
        isShow.value //1上架，2下架，3删除
    ) {
        case 1:
            await productUpstate({ product_ids: params });
            ElMessage.success('上架成功');
            delId.value = [];
            checkList.value = [];
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            tableRef.value?.clearSelection();
            break;
        case 2:
            await productDownstate({ product_ids: params });
            ElMessage.success('下架成功');
            delId.value = [];
            checkList.value = [];
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            tableRef.value?.clearSelection();
            break;
        case 3:
            await productDel({ product_id: delId.value });
            ElMessage.success('删除成功');
            delId.value = [];
            checkList.value = [];
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            tableRef.value?.clearSelection();
            break;
    }
};

// 跳转新建
const newProductList = () => {
    router.push({
        path: '/salesleads/salesmanagement/productmanagement/create'
    });
};
// 查看
const look = (v: any) => {
    router.push({
        path: '/salesleads/salesmanagement/productmanagement/create',
        query: { type: 'look', id: v.product_id }
    });
};
// 编辑
const edit = (v: any) => {
    router.push({
        path: '/salesleads/salesmanagement/productmanagement/create',
        query: { type: 'edit', id: v.product_id }
    });
};
// 预览
const preview = async (v: any) => {
    const res = await productPreview({ product_id: v.product_id });
    productPopupData.value = res;
    productPopupRef.value.drawer = true;
};

// 导入弹窗
const cancelHandel = () => {
    appDialog.visible = false;
    formData.product_url = '';
    formData.product_name = '';
};
const submitHandel = async () => {
    if (formData.product_name !== '' && formData.product_url !== '') {
        appDialog.visible = false;
    } else {
        ElMessage.error('请选择需要上传的文件');
        return;
    }
    try {
        await productImport({ product_url: formData.product_url });
        tableRef.value?.clearSelection();
        tableRef.value?.reload();
        ElMessage.success('导入成功');
    } catch (err) {
        if (formData.product_name !== '' && err?.msg) {
            ElMessage.warning(`${err.msg}`);
            formData.product_url = '';
            formData.product_name = '';
            tableRef.value?.reload();
        }
    }
    formData.product_url = '';
    formData.product_name = '';
};

//导入产品弹窗
const appDialog = reactive({
    visible: false,
    title: '导入产品',
    width: '600px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '导入'
});
const handleFile: UploadProps['onChange'] = async (file: any) => {
    const res = await uploadFile2({
        file: file.raw,
        fileName: file.name
    });
    formData.product_url = res.url;
    formData.product_name = res.name;
};

// 下载模板规范
const download = async () => {
    downFile('https://static.scrm.keyid.cn/keyid-scrm-server/template/sale_product_import.xlsx', '产品模板.xlsx');
};
// 导入产品
const ImportStore = () => {
    appDialog.visible = true;
};
// 删除
const del = () => {
    formData.product_url = '';
    formData.product_name = '';
};

onActivated((val: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>

<style lang="scss" scoped>
.product_management_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}

.dia_text {
    color: #696969;
    font-size: 14px;
    margin-top: 15px;
}

.file_info {
    font-size: 14px;
    justify-content: space-between;
    box-sizing: border-box;
    background: #eaeaea;
    display: flex;
    padding: 10px;
    align-items: center;

    img {
        width: 20px;
        height: 20px;
        vertical-align: middle;
        margin-right: 7px;
    }

    .del_icon {
        cursor: pointer;
        margin-left: 5px;
    }
}

.file {
    .el-button {
        margin: 0 16px;
    }

    :deep(.el-upload-list) {
        display: none;
    }
}

.btn_item {
    width: 60px;
    padding: 6px 20px;
    text-align: center;
    background: #f9f9f9;
    border-radius: 2px;
    border: 1px solid #eaeaea;
    cursor: pointer;
    font-size: 14px;
    margin-top: 24px;
    margin: 0 12px;
}
</style>
